﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Gedea.Model.Entities;
using System.Text.RegularExpressions;

namespace Gedea.Service.Services
{
    public class TextFileService
    {
        int count = 0;
        #region PublicMethods
        public void Generate(List<Customer> customers)
        {
            string fileRoot = string.Format("{0}\\{1}",
                    Credentials.primaryRoot + DateTime.Now.Year,
                    Credentials.GenerationFolder);

            string fileName = string.Format("EBT_{0}_{1}_{2}_{3}_{4}_{5}_{6}.txt",
                    Credentials.currentUser.Name,
                    DateTime.Now.Year,
                    DateTime.Now.Month,
                    DateTime.Now.Day,
                    DateTime.Now.Hour,
                    DateTime.Now.Minute,
                    DateTime.Now.Second);
            
            using (StreamWriter sr = new StreamWriter(fileRoot + fileName))
            {
                customers.ForEach(x => sr.WriteLine(SetBankTextLine(Credentials.currentUser, x)));
            }

            //IML ruta configurable respecto al usuario. Al cambiarla que testee si tiene los permisos necesarios.
            File.Copy(fileRoot + fileName, Credentials.DesktopRoot + fileName);

            File.SetAttributes(fileRoot + fileName, FileAttributes.ReadOnly);
        }

        public List<Customer> Leer(string root)
        {
            List<Customer> res = new List<Customer>();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(root))
            {
                string rrr = sr.ReadToEnd();
                throw new NotImplementedException();
                //res = Regex.Split(rrr, "\n").ToList().ToString(); //IML
                //foo.Substring(0, 5);
                res.RemoveAt(res.Count - 1);
            }

            return res;
        }
        #endregion
        #region PrivateMethods
        private string SetBankTextLine(User user, Customer customer)
        {
            string res = GetInternalBankCode(customer);
            res += GetExpirationDate(customer);
            res += StringFormat("", 6, '0', true); //InternalTransactionReference
            res += GetIdForBank(customer);
            res += "P";
            res += GetCbu(customer.Cbu);
            res += GetAmount(customer);
            res += GetCuit(user.Cuit);
            res += GetBenefit(user.Benefit); //Descripcion de la prestacion
            res += GetArea(customer.AreaId);
            res += GetCount();
            res += StringFormat("", 5, ' ', true);
            res += StringFormat("", 15, ' ', true);
            res += StringFormat("", 22, ' ', true);//Nuevo identificador del cliente
            res += StringFormat("", 3, ' ', true); //Codigo del rechazo
            res += GetNameForBank(user.NameForBank);

            return res;
        }

        private string GetCount()
        {
            count += 1;
            return IntFormat(count , 3);
        }

        private string GetCuit(string cuit)
        {
            return StringFormat(cuit, 11, '0', true);
        }

        private string GetArea(int areaId)
        {
            return StringFormat(new AreaService().Get(areaId).DebitUnivocalReference, 7, '0', false);
        }

        private string GetCbu(string cbu)
        {
            return StringFormat(cbu, 22, '0', true);
        }

        private string GetInternalBankCode(Customer customer)
        {
            return customer.Cbu.Remove(3) == "014" ? "71" : "51";
        }

        private string GetExpirationDate(Customer customer)
        {
            return IntFormat(customer.ExpirationDate.Day, 2)
                + IntFormat(customer.ExpirationDate.Month, 2)
                + IntFormat(customer.ExpirationDate.Year, 4);
        }

        private string GetIdForBank(Customer customer)
        {
            return StringFormat(customer.IdForBank, 22, ' ', false);
        }

        private string GetAmount(Customer customer)
        {
            return StringFormat(customer.Amount.ToString(), 10, '0', true);
        }

        private string GetBenefit(string benef)
        {
            return StringFormat(benef, 10, ' ', false);
        }

        private string GetNameForBank(string nameForBank)
        {
            return StringFormat(nameForBank, 16, ' ', false);
        }

        private string IntFormat(int value, int length)
        {
            return StringFormat(value.ToString(), length, '0', true);
        }

        private string StringFormat(string value, int length, char app, bool appGoesBefore)
        {
            if (value.Length < length)
            {
                string append = "";
                for (int i = 0; i < length - value.Length; i++)
                {
                    append += app;
                }
                value = appGoesBefore ? append + value : value + append;
            }
            //return value.Remove(length);
            return value;
        }
        #endregion
    }
}
